package com.windaka.elements.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <li>
 * <p>
 * word 根据模板 替换模板内容 导出word
 * <strong>示例1: 根据模板导出</strong> <br>
 * WordUtils.exportWordByTemplate(templateFile, placeholderMap);
 * 结果: 根据模板和数据生成了新的word文档并写出
 * </p>
 * </li>
 * @author song
 * @date 14:38 2022/5/6
 **/
@Slf4j
public class WordUtils {

    private WordUtils() {
    }

    /**
     * <li>
     * <p>
     * word 根据模板 替换模板内容 导出word
     * <strong>示例1: 根据模板导出</strong> <br>
     * WordUtils.exportWordByTemplate(templateFile, placeholderMap);
     * 结果: 根据模板和数据生成了新的word文档并写出
     * </p>
     * </li>
     * @author song
     * @date 18:45 2022/5/6
     **/
    public static Boolean exportWordByTemplate(String filePath, String outPath, Map<String, String> placeholderMap) {
        File templateFile = new File(filePath);
        // 判断模板文件是否存在
        if (!templateFile.exists()) {
            return false;
        }
        // 获取占位符的keySet
        Set<String> keySet = placeholderMap.keySet();
        // 操作IO
        try (
                // 操作word
                XWPFDocument document = new XWPFDocument(new FileInputStream(templateFile));
                // 写出的路径
                FileOutputStream fileOutputStream = new FileOutputStream(outPath);
                // 缓冲流
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)
        ) {
            // 获得word当中的段落
            List<XWPFParagraph> paragraphList = document.getParagraphs();
            // 遍历每个段落
            for (XWPFParagraph paragraph : paragraphList) {
                // 拿到每行的信息 XWPFRun
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    String eachText = run.getText(run.getTextPosition());
                    // 遍历keySet 如果存在则替换
                    for (String s : keySet) {
                        String replaceStr = placeholderMap.getOrDefault(s, "");
                        if (CheckParamUtils.isNullOrEmpty(replaceStr)) {
                            replaceStr = "";
                        }
                        eachText = eachText.replaceAll(s, replaceStr);
                    }
                    run.setText(eachText, 0);
                }
            }
            List<XWPFTable> tableList = document.getTables();
            for (XWPFTable table : tableList) {
                List<XWPFTableRow> rowsList = table.getRows();
                for (XWPFTableRow row : rowsList) {
                    List<XWPFTableCell> cellList = row.getTableCells();
                    for (XWPFTableCell cell : cellList) {
                        String content = cell.getText();
                        for (String s : keySet) {
                            String replaceStr = placeholderMap.getOrDefault(s, "");
                            boolean flag = false;
                            if (CheckParamUtils.isNullOrEmpty(replaceStr)) {
                                replaceStr = "";
                            }
                            if (content.contains(s)) {
                                flag = true;
                            }
                            content = content.replaceAll(s, replaceStr);
                            if (flag) {
                                cell.removeParagraph(0);
                                cell.setText(content);
                            }
                        }
                    }
                }
            }
            // 写出
            document.write(bufferedOutputStream);
        } catch (Exception e) {
            log.error("[WordUtils => exportWordByTemplate 执行失败 {}]", e.getMessage());
            return false;
        }
        return true;
    }

}
